<?php

namespace app\common\controller;

use think\App;
use think\exception\HttpResponseException;
use HttpEncodingException;
use think\Response;
use app\common\model\UserData as UserDataModel;
use think\facade\Cache;
use think\facade\Db;

class MobileCommunication
{

    public function initialize()
    {
    }
    /**
     * 操作成功跳转的快捷方法
     */
    public function dataReturn($msg = '',$code = '', $data = '')
    {

        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];

        throw new HttpResponseException(json($result));
    }

//    public function GetMobileToken()
//    {
//        $params = [
//            "ASKACC"=>"yidong",
//            "ASKPWD"=>"YD!@#$",
//            "CHANNEL_CODE"=>"yidong",
//            "REQURL"=>"getTokenLocalService"
//        ];
//
//        $token = $this->CurlPost(config('app.mobile_communication_CHANNEL_link'),$params,true);
//        if(!$token){
//            $this->dataReturn('获取信息失败',-1,$token);
//        }
//        $token = json_decode($token,true);
//        if (!isset($token['resultCode']) || $token['resultCode'] != 0){
//            $this->dataReturn($token['resultMsg'],-1);
//        }
//        Cache::set('laner_mobile_token',$token['resultObj']['TOKEN'],60*25);
//        return $token['resultObj']['TOKEN'];
//    }
//
//    public function MobileSend($post)
//    {
//        $laner_mobile_token = Cache::get('laner_mobile_token');
//        if (!$laner_mobile_token || empty($laner_mobile_token)){
//           $laner_mobile_token = $this->GetMobileToken();
//        }
//        $params = [
//           "ASKACC"=>"yidong",
//           "ASKPWD"=>"YD!@#$",
//           "CHANNEL_CODE"=>"yidong",
//           "REQURL"=>"addBusSendMsgService",
//           "TOKEN"=>$laner_mobile_token,
//           "MOBILE"=>$post['mobile'],
//           "BusiCode"=>isset($post['busCode']) ? $post['busCode'] : '12671'
//        ];
//        $mobile_info = $this->CurlPost(config('app.mobile_communication_CHANNEL_link'),$params,true);
//        $mobile_info = json_decode($mobile_info,true);
//        if (!isset($mobile_info['resultCode']) || $mobile_info['resultCode'] != 0){
//            $log['mobile'] = $post['mobile'];
//            $log['msg'] = $mobile_info['resultMsg'];
//            $log['content'] = json_encode($mobile_info);
//            $log['code'] = isset($post['busCode']) ? $post['busCode'] : '12671';
//            $log['ip'] = $this->getIp();
//            $log['add_date'] = date('Y-m-d H:i:s',time());
//            $log['add_time'] = time();
//            Db::name('msgsend_log')->insertGetId($log);
//            $this->dataReturn($mobile_info['resultMsg'],-1,$mobile_info);
//        }
//        $this->dataReturn('发送成功',0);
//    }
//
//    public function Reverse($post)
//    {
//        $laner_mobile_token = Cache::get('laner_mobile_token');
//        if (!$laner_mobile_token || empty($laner_mobile_token)){
//           $laner_mobile_token = $this->GetMobileToken();
//        }
//        $busCode = isset($post['busCode']) ? $post['busCode'] : '12671';
//        $params = [
//            "ASKACC"=>"yidong",
//            "ASKPWD"=>"YD!@#$",
//            "CHANNEL_CODE"=>"yidong",
//            "REQURL"=>"addBusCheckMsgService",
//            "MOBILE"=>$post['mobile'],
//            "optType"=>"1",
//            "operType"=>"1",
//            "onlyCheck"=>"2",
//            "busiCode"=>$busCode,
//            "smsCode"=>$post['code'],
//            "TOKEN"=>$laner_mobile_token,
//            "UUID"=>Cache::get('laner_mobile_token'),
//            "OPERID"=>'hb_yidong'
//        ];
//        $mobile_info = $this->CurlPost(config('app.mobile_communication_CHANNEL_link'),$params,true);
//        $mobile_info = json_decode($mobile_info,true);
//        if (!isset($mobile_info['resultCode']) || $mobile_info['resultCode'] != 0){
//            $this->dataReturn($mobile_info['resultMsg'],-1,$mobile_info);
//        }
//        //添加
//        $model = new UserDataModel();
//        $data = [
//            "mobile"=>$post['mobile'],
//            "p_id"=>isset($post['p_id']) ? $post['p_id'] : 0,
//            "bus_code"=>$busCode,
//            "create_time"=>time()
//        ];
//        $result = $model->insertGetId($data);
//        if ($result) {
//            if(!empty($post['order_sn'])){
//                $dataR['order_sn'] = $post['order_sn'];
//                $dataR['transaction_id'] = array('111'.$post['mobile']);
//                $log['add_date'] = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
//                $log['add_time'] = $_SERVER['REQUEST_TIME'];
//                $res = $this->CurlPost(config('app.reback_link'),$dataR,true);
//                $log['mobile'] = $post['mobile'];
//                $log['content'] = $res;
//                $res =json_decode($res,true);
//                $log['status'] = $res['status'];
//                $log['end_date'] = date('Y-m-d H:i:s',time());
//                $log['end_time'] = time();
//                Db::name('request_log')->insertGetId($log);
//            }
//            $this->dataReturn('办理成功',0,$mobile_info);
//        } else {
//            $this->dataReturn('办理失败！',-1,$mobile_info);
//        }
//    }

    public function GetMobileToken()
    {
        $params = [
            "client_id"=>"20210104000000001",
            "grant_type"=>"client_credentials",
            "client_secret"=>"3gcc369397ba873b1815479ce46ffa64"
        ];

        $token = $this->CurlPost('https://218.207.75.17:8060/OAuth/restOauth2Server/access_token',$params);
        if(!$token){
            $this->dataReturn('获取信息失败',-1,$token);
        }
        $token = json_decode($token,true);
        if (!isset($token['access_token']) || empty($token['access_token'])){
            $this->dataReturn('token获取失败！',-1);
        }
        Cache::set('nengkai_mobile_token',$token['access_token'],3500);
        return $token['access_token'];
    }

    public function MobileSend($post)
    {
        $nengkai_mobile_token = Cache::get('nengkai_mobile_token');
        if (!$nengkai_mobile_token || empty($nengkai_mobile_token)){
            $nengkai_mobile_token = $this->GetMobileToken();
        }
        $params = [
            "TELNUM"=>$post['mobile'],
            "CHANNELID"=>"bsacXSDLSydkj",
        ];
        $mobile_info = $this->CurlPost('https://218.207.75.17:8060/OpenEbus/httpService/SubsAuthService?access_token='.$nengkai_mobile_token.'&method=SendSmsRandomPass&format=json',$params,true);
        $mobile_info = json_decode($mobile_info,true);
        $log['mobile'] = $post['mobile'];
        $log['msg'] = $mobile_info['res_desc'];
        $log['content'] = json_encode($mobile_info);
        $log['code'] = isset($post['busCode']) ? $post['busCode'] : '12671';
        $log['status'] = $mobile_info['res_code'];
        $log['ip'] = $this->getIp();
        $log['add_date'] = date('Y-m-d H:i:s',time());
        $log['add_time'] = time();
        Db::name('msgsend_log')->insertGetId($log);
        if (!isset($mobile_info['res_code']) || $mobile_info['res_code'] != 0){
            $this->dataReturn($mobile_info['res_desc'],-1,$mobile_info);
        }
        $this->dataReturn('发送成功',0);
    }

    public function Reverse($post)
    {
        $nengkai_mobile_token = Cache::get('nengkai_mobile_token');
        if (!$nengkai_mobile_token || empty($nengkai_mobile_token)){
            $nengkai_mobile_token = $this->GetMobileToken();
        }
        $busCode = isset($post['busCode']) ? $post['busCode'] : '12671';
        $params = [
            "TELNUM"=>$post['mobile'],
            "OPERTYPE"=>"PCOpRec",
            "PRODUCTINFO"=>[
                [
                    "SUBSSERVATTRLIST"=>'',
                    "PRODUCTCODE"=>'12671',
                    "SUBSPRIVATTRLIST"=>''
                ]
            ],
            "ONLYCHECK"=>"2",
            "SMSRANDOMPASS"=>$post['code'],
            "CHANNELID"=>'bsacXSDLSydkj',
            "AuthCheckType"=>'AuthCheckA',
            "OPERID"=>'hb_yidong'
        ];
        $reverse_log['add_date'] = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
        $reverse_log['add_time'] = $_SERVER['REQUEST_TIME'];
        $mobile_info = $this->CurlPost('https://218.207.75.17:8060/OpenEbus/httpService/UserService?access_token='.$nengkai_mobile_token.'&method=IntAppendProductRecBySmsCHK&format=json',$params,true);
        if(empty($mobile_info)){
            $this->dataReturn('办理失败！',-1);
        }
        $mobile_info = iconv("EUC-CN", "UTF-8", $mobile_info);
        $reverse_log['mobile'] = $post['mobile'];
        $reverse_log['content'] = $mobile_info;
        $reverse_log['end_date'] = date('Y-m-d H:i:s',time());
        $reverse_log['end_time'] = time();
        Db::name('reverse_log')->insertGetId($reverse_log);
        $mobile_info = json_decode($mobile_info,true);
        if (!isset($mobile_info['res_code']) || $mobile_info['res_code'] != 0){
            $this->dataReturn($mobile_info['res_desc'],-1,$mobile_info);
        }
        //添加
        $model = new UserDataModel();
        $data = [
            "mobile"=>$post['mobile'],
            "p_id"=>isset($post['p_id']) ? $post['p_id'] : 0,
            "bus_code"=>$busCode,
            "create_time"=>time()
        ];
        $result = $model->insertGetId($data);
        if ($result) {
            if(!empty($post['order_sn'])){
                $dataR['order_sn'] = $post['order_sn'];
                $dataR['transaction_id'] = array('111'.$post['mobile']);
                $log['add_date'] = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
                $log['add_time'] = $_SERVER['REQUEST_TIME'];
                $res = $this->CurlPost(config('app.reback_link'),$dataR,true);
                $log['mobile'] = $post['mobile'];
                $log['content'] = $res;
                $res =json_decode($res,true);
                $log['status'] = $res['status'];
                $log['end_date'] = date('Y-m-d H:i:s',time());
                $log['end_time'] = time();
                Db::name('request_log')->insertGetId($log);
            }
            $auth = new \app\common\library\Auth();
            if(empty($post['token'])){
                $user = \app\common\model\User::where('mobile',$post['mobile'])->find();
                if ($user) {
                    //如果已经有账号则直接登录
                    $ret = $auth->direct($user->id);
                } else {
                    $ret = $auth->register($post['mobile']);
                }
            }
            $info = ['userinfo' => $auth->getUserinfo()];
            $this->dataReturn('办理成功',0,$info);
        } else {
            $this->dataReturn('办理失败！',-1,$mobile_info);
        }
    }

    public function MobileLogin($params)
    {
        $params = [
            "timestamp"=>date('YmdHis'),
            "signature"=>md5(config('app.migu.channelCode').date('YmdHis').config('app.migu.secret')),
            "channelCode"=>"014X00I",
            "msisdn"=>$params['mobile'],
            "key"=>config('app.migu.key'),
            "callBackUrl"=>$params['url']
        ];
        $result = file_get_contents(config('app.migu.loginLink').urlencode(json_encode($params)));
        $result = json_decode($result,true);
        if($result['resCode'] != '000000'){
            $this->dataReturn($result['resMsg'],-1,$result);
        }
        $this->dataReturn('成功',0,$result);
    }

    public function IsReverse($params)
    {
        $params = [
            "timestamp"=>date('YmdHis'),
            "signature"=>md5(config('app.migu.channelCode').date('YmdHis').config('app.migu.secret')),
            "channelCode"=>config('app.migu.channelCode'),
            "serviceId"=>$params['serviceId'],
            "token"=>$params['tokenT']
        ];
        $url = config('app.migu.isReverseLink').urlencode(json_encode($params));
        $result = json_decode(file_get_contents($url),true);
        $result['url'] = $url;
        if($result['resCode'] == '999009'){
            $this->dataReturn($result['resMsg'],401,$result);
        }
        if($result['resCode'] != '000000'){
            $this->dataReturn($result['resMsg'],-1,$result);
        }
        $this->dataReturn('成功',0,$result);
    }

    public function SetVideo($params)
    {
        $params = [
            "timestamp"=>date('YmdHis'),
            "signature"=>md5(config('app.migu.channelCode').date('YmdHis').config('app.migu.secret')),
            "channelCode"=>config('app.migu.channelCode'),
            "serviceId"=>$params['serviceId'],
            "token"=>$params['tokenT'],
            "contentId"=>$params['contentId'],
            "name"=>'miguOrderFreeVrbt'
        ];
        $url = config('app.migu.setVideoLink').urlencode(json_encode($params));
        $result = json_decode(file_get_contents($url),true);
        $result['url'] = $url;
        if($result['resCode'] == '999009'){
            $this->dataReturn($result['resMsg'],401,$result);
        }
        if($result['resCode'] != '000000'){
            $this->dataReturn($result['resMsg'],-1,$result);
        }
        $this->dataReturn('成功',0,$result);
    }

    /**
     */
    public function CurlPost($url, $post = [], $is_json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //连接超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);

        // 是否 json
        if($is_json)
        {
            $data_string = json_encode($post);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    "Content-Type: application/json; charset=utf-8",
                    "Content-Length: " . strlen($data_string)
                )
            );
        } else {
            if(!empty($post)){
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    "Content-Type: application/x-www-form-urlencoded",
                    "cache-control: no-cache"
                )
            );
        }
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * 获取ip
     */
    function getIp()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
}